package com.platform.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.sql.SqlUtil;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.page.PageDomain;
import com.platform.common.core.web.page.TableDataInfo;
import com.platform.common.core.web.page.TableSupport;
import com.platform.common.security.utils.AESUtil_SC;
import com.platform.file.constant.SysFileConstants;
import com.platform.file.mapper.EncryCompexMapper;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Slf4j
@RestController
@RequestMapping("/fileEncrypt")
public class FileEncryptController extends BaseController {

    @Autowired
    private EncryCompexMapper encryCompexMapper;

    @Async
    @PostMapping("/encry")
    public void encryFilePath(@RequestBody Map<String,Object> map){
        /*String tablename,String filePathCol,String keyId,String domain*/
        try {
            PageHelper.startPage(1, 200, null);
            Map param=new HashMap();
            String filePathCol=(String)map.get("filePathCol");
            String bucketName=(String)map.get("bucketName");
            String domain=(String)map.get("domain");
            List<String> listCols=new ArrayList<String>();
            listCols.add((String)map.get("filePathCol"));
            listCols.add((String)map.get("keyId"));
            param.put("tablenamestr", map.get("tablename"));
            param.put("listCols", listCols);
            param.put("keyId",map.get("keyId"));
            List<Map> listdata=encryCompexMapper.selectDataFileEncry(param);
            TableDataInfo res=getDataTable(listdata);
            Map paramup=new HashMap();
            paramup.put("tablenamestr", map.get("tablename"));
            Map<String, Object> mapUpcols=new HashMap<String, Object>();
            for(int i=0;i<listdata.size();i++){
                Map data=listdata.get(i);
                try {
                    String filePath=(String)data.get(filePathCol);
                    if(!StringUtils.isEmpty(filePath)&&filePath.indexOf("/")!=-1){
                        if(!StringUtils.isEmpty(domain)){
                            filePath=filePath.replace(domain,"");
                        }
                        mapUpcols.put((String)map.get("keyId"),data.get((String)map.get("keyId")));
                        paramup.put("mapUpcols",mapUpcols);
                        String enfilePathCol=null;
                        if(StringUtils.isEmpty(bucketName)){
                            enfilePathCol=AESUtil_SC.encryptNoBase64(filePath,"dLC5BZUwZXCsVReL");
                        }else{
                            enfilePathCol=AESUtil_SC.encryptNoBase64(bucketName+"/"+filePath,"dLC5BZUwZXCsVReL");
                        }
                        //String enfilePathCol=AESUtil_SC.encryptNoBase64(bucketName+"/"+(String)data.get(filePathCol),SysFileConstants.FILESECRET);
                        data.remove(filePathCol);
                        data.remove(map.get("keyId"));
                        data.put((String)map.get("filePathUpdCol"),enfilePathCol);
                        paramup.put("params",data);
                        encryCompexMapper.updateDataFileEncry(paramup);
                    }else{
                        log.error("数据:{}已加密",JSONObject.toJSONString(data));
                    }
                }catch (Exception e){
                    log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                }

            }
            int pages=getPages(res.getTotal(),200);
            for(int j=2;j<=pages;j++){
                PageHelper.startPage(j, 200, null);
                List<Map> listdatas=encryCompexMapper.selectDataFileEncry(param);
                for(int i=0;i<listdatas.size();i++){
                    Map data=listdatas.get(i);
                    try {
                        String filePath=(String)data.get(filePathCol);
                        if(!StringUtils.isEmpty(domain)){
                            filePath=filePath.replace(domain,"");
                        }
                        if(!StringUtils.isEmpty(filePath)&&filePath.indexOf("/")!=-1) {
                            mapUpcols.put((String) map.get("keyId"), data.get((String) map.get("keyId")));
                            paramup.put("mapUpcols", mapUpcols);
                            String enfilePathCol=null;
                            if(StringUtils.isEmpty(bucketName)){
                                enfilePathCol=AESUtil_SC.encryptNoBase64((String)data.get(filePathCol),"dLC5BZUwZXCsVReL");
                            }else{
                                enfilePathCol=AESUtil_SC.encryptNoBase64(bucketName+"/"+(String)data.get(filePathCol),"dLC5BZUwZXCsVReL");
                            }
                            //String enfilePathCol = AESUtil_SC.encryptNoBase64(bucketName + "/" + (String) data.get(filePathCol), SysFileConstants.FILESECRET);
                            data.remove(filePathCol);
                            data.remove(map.get("keyId"));
                            data.put((String) map.get("filePathUpdCol"), enfilePathCol);
                            paramup.put("params", data);
                            encryCompexMapper.updateDataFileEncry(paramup);
                          }
                       }catch (Exception e){
                          log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Async
    @PostMapping("/encryBlob")
    public void encryBolbFilePath(@RequestBody Map<String,Object> map){
        /*String tablename,String filePathCol,String keyId,String domain*/
        try {
            PageHelper.startPage(1, 10, null);
            Map param=new HashMap();
            String filePathCol=(String)map.get("filePathCol");
            String bucketName=(String)map.get("bucketName");
            String domain=(String)map.get("domain");
            List<String> listCols=new ArrayList<String>();
            listCols.add((String)map.get("filePathCol"));
            listCols.add((String)map.get("keyId"));
            param.put("tablenamestr", map.get("tablename"));
            param.put("listCols", listCols);
            param.put("keyId",map.get("keyId"));
            List<Map> listdata=encryCompexMapper.selectDataFileEncry(param);
            TableDataInfo res=getDataTable(listdata);
            Map paramup=new HashMap();
            paramup.put("tablenamestr", map.get("tablename"));
            Map<String, Object> mapUpcols=new HashMap<String, Object>();
            for(int i=0;i<listdata.size();i++){
                Map data=listdata.get(i);
                try {
                    //String contenthtml=(String)data.get(filePathCol);
                    String contenthtml=new String((byte[])data.get(filePathCol));
                    Document doc= Jsoup.parse(contenthtml);
                    Elements imgTags=doc.select("img");
                    Set<String> filePaths=new LinkedHashSet<String>();
                    if(imgTags!=null&&imgTags.size()>0){
                        for(Element imgTag : imgTags){
                            String src=imgTag.attr("src");
                            filePaths.add(src);
                        }
                    }
                    for(String filePath:filePaths){
                        String filePathNew="";
                        if(!StringUtils.isEmpty(domain)){
                            filePathNew=filePath.replace(domain,"");
                        }
                        if(filePath.indexOf("/")!=-1){
                            String enfilePathCol=null;
                            if(StringUtils.isEmpty(bucketName)){
                                enfilePathCol=AESUtil_SC.encryptNoBase64(filePathNew,"dLC5BZUwZXCsVReL");
                            }else{
                                enfilePathCol=AESUtil_SC.encryptNoBase64(bucketName+"/"+filePathNew,"dLC5BZUwZXCsVReL");
                            }
                            contenthtml=contenthtml.replaceAll(filePath,enfilePathCol);
                        }
                    }

                    if(imgTags!=null&&imgTags.size()>0){
                        mapUpcols.put((String)map.get("keyId"),data.get((String)map.get("keyId")));
                        paramup.put("mapUpcols",mapUpcols);
                        data.remove(filePathCol);
                        data.remove(map.get("keyId"));
                        data.put((String)map.get("filePathUpdCol"),contenthtml);
                        paramup.put("params",data);
                        encryCompexMapper.updateDataFileEncry(paramup);
                    }
                }catch (Exception e){
                    log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                }
            }
            int pages=getPages(res.getTotal(),10);
            for(int j=2;j<=pages;j++){
                PageHelper.startPage(j, 10, null);
                List<Map> listdatas=encryCompexMapper.selectDataFileEncry(param);
                for(int i=0;i<listdatas.size();i++){
                    Map data=listdatas.get(i);
                    try {
                        String contenthtml=new String((byte[])data.get(filePathCol));
                        Document doc= Jsoup.parse(contenthtml);
                        Elements imgTags=doc.select("img");
                        Set<String> filePaths=new LinkedHashSet<String>();
                        if(imgTags!=null&&imgTags.size()>0){
                            for(Element imgTag : imgTags){
                                String src=imgTag.attr("src");
                                filePaths.add(src);
                            }
                        }
                        for(String filePath:filePaths){
                            String filePathNew="";
                            if(!StringUtils.isEmpty(domain)){
                                filePathNew=filePath.replace(domain,"");
                            }
                            if(filePath.indexOf("/")!=-1){
                                String enfilePathCol=null;
                                if(StringUtils.isEmpty(bucketName)){
                                    enfilePathCol=AESUtil_SC.encryptNoBase64(filePathNew,"dLC5BZUwZXCsVReL");
                                }else{
                                    enfilePathCol=AESUtil_SC.encryptNoBase64(bucketName+"/"+filePathNew,"dLC5BZUwZXCsVReL");
                                }
                                contenthtml=contenthtml.replaceAll(filePath,enfilePathCol);
                            }
                        }

                        if(imgTags!=null&&imgTags.size()>0){
                            mapUpcols.put((String)map.get("keyId"),data.get((String)map.get("keyId")));
                            paramup.put("mapUpcols",mapUpcols);
                            data.remove(filePathCol);
                            data.remove(map.get("keyId"));
                            data.put((String)map.get("filePathUpdCol"),contenthtml);
                            paramup.put("params",data);
                            encryCompexMapper.updateDataFileEncry(paramup);
                        }
                    }catch (Exception e){
                        log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    @Async
    @PostMapping("/updateBlobPath")
    public void updateBlobPath(@RequestBody Map<String,Object> map){
        try {
            PageHelper.startPage(1, 10, null);
            Map param=new HashMap();
            String filePathCol=(String)map.get("filePathCol");
            List<String> listCols=new ArrayList<String>();
            listCols.add((String)map.get("filePathCol"));
            listCols.add((String)map.get("keyId"));
            param.put("tablenamestr", map.get("tablename"));
            param.put("listCols", listCols);
            param.put("keyId",map.get("keyId"));
            List<Map> listdata=encryCompexMapper.selectDataFileEncry(param);
            TableDataInfo res=getDataTable(listdata);
            Map paramup=new HashMap();
            paramup.put("tablenamestr", map.get("tablename"));
            Map<String, Object> mapUpcols=new HashMap<String, Object>();
            for(int i=0;i<listdata.size();i++){
                Map data=listdata.get(i);
                try {
                    //String contenthtml=(String)data.get(filePathCol);
                    String contenthtml=new String((byte[])data.get(filePathCol));
                    /**
                    Document doc= Jsoup.parse(contenthtml);
                    Elements imgTags=doc.select("img");
                    Set<String> filePaths=new LinkedHashSet<String>();
                    if(imgTags!=null&&imgTags.size()>0){
                        for(Element imgTag : imgTags){
                            String src=imgTag.attr("src");
                            filePaths.add(src);
                        }
                    }
                    for(String filePath:filePaths){
                        if(filePath.indexOf("/")!=-1){
                            String enfilePathCol=filePath.replace("public/","nopermission/");
                            contenthtml=contenthtml.replaceAll(filePath,enfilePathCol);
                        }
                    }**/
                    contenthtml=contenthtml.replaceAll("public/","nopermission/");
                    mapUpcols.put((String)map.get("keyId"),data.get((String)map.get("keyId")));
                    paramup.put("mapUpcols",mapUpcols);
                    data.remove(filePathCol);
                    data.remove(map.get("keyId"));
                    data.put((String)map.get("filePathUpdCol"),contenthtml);
                    paramup.put("params",data);
                    encryCompexMapper.updateDataFileEncry(paramup);
                }catch (Exception e){
                    log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                }
            }
            int pages=getPages(res.getTotal(),10);
            for(int j=2;j<=pages;j++){
                PageHelper.startPage(j, 10, null);
                List<Map> listdatas=encryCompexMapper.selectDataFileEncry(param);
                for(int i=0;i<listdatas.size();i++){
                    Map data=listdatas.get(i);
                    try {
                        String contenthtml=new String((byte[])data.get(filePathCol));
                        /**
                        Document doc= Jsoup.parse(contenthtml);
                        Elements imgTags=doc.select("img");
                        Set<String> filePaths=new LinkedHashSet<String>();
                        if(imgTags!=null&&imgTags.size()>0){
                            for(Element imgTag : imgTags){
                                String src=imgTag.attr("src");
                                filePaths.add(src);
                            }
                        }
                        for(String filePath:filePaths){
                            if(filePath.indexOf("/")!=-1){
                                String enfilePathCol=filePath.replace("public/","nopermission/");
                                contenthtml=contenthtml.replaceAll(filePath,enfilePathCol);
                            }
                        }**/
                        contenthtml=contenthtml.replaceAll("public/","nopermission/");
                        mapUpcols.put((String)map.get("keyId"),data.get((String)map.get("keyId")));
                        paramup.put("mapUpcols",mapUpcols);
                        data.remove(filePathCol);
                        data.remove(map.get("keyId"));
                        data.put((String)map.get("filePathUpdCol"),contenthtml);
                        paramup.put("params",data);
                        encryCompexMapper.updateDataFileEncry(paramup);
                    }catch (Exception e){
                        log.error("加密异常数据:{},异常信息：{}",JSONObject.toJSONString(data),e.getMessage());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public int getPages(long total,int pagesize){
        int totalNum=(int)total;
        int pages = (totalNum%pagesize)==0?(totalNum/pagesize):(totalNum/pagesize+1);
        return pages;
    }

}
